#!/usr/local/bin/python
# -*- coding: utf-8 -*-

### Imports ###
import os,sys

### Functions ###

#################################################
## This block has been stolen from some source ##
#################################################
# Default maximum for the number of available file descriptors.
MAXFD = 1024

# The standard I/O file descriptors are redirected to /dev/null by default.
if (hasattr(os, "devnull")):
  REDIRECT_TO = os.devnull
else:
  REDIRECT_TO = "/dev/null"

## Function for daemonize application
def createDaemon():
  """Detach a process from the controlling terminal and run it in the
  background as a daemon.
  """
  try:
    pid = os.fork()
  except OSError, e:
    raise Exception, "%s [%d]" % (e.strerror, e.errno)

  if (pid == 0):       # The first child.
    os.setsid()
    # import signal           # Set handlers for asynchronous events.
    # signal.signal(signal.SIGHUP, signal.SIG_IGN)
    try:
      pid = os.fork()        # Fork a second child.
    except OSError, e:
      raise Exception, "%s [%d]" % (e.strerror, e.errno)
    if (pid != 0):    # The second child.
      os._exit(0)    # Exit parent (the first child) of the second child.
  else:
    os._exit(0)       # Exit parent of the first child.

  import resource              # Resource usage information.
  maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[1]
  if (maxfd == resource.RLIM_INFINITY):
    maxfd = MAXFD

  # Iterate through and close all file descriptors.
  for fd in range(0, maxfd):
    try:
      os.close(fd)
    except OSError:   # ERROR, fd wasn't open to begin with (ignored)
      pass
    return True

#############################################
###      End of stolen block of code      ###
#############################################

### Functions ###
